package org.flown.novel.controller;

import jakarta.servlet.http.HttpSession;
import org.flown.novel.data.User;
import org.flown.novel.service.ServiceResult;
import org.flown.novel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@RequestMapping("/user")
@Controller
public class UserController
{
    @Autowired
    private UserService service;

    @ResponseBody
    @PostMapping("/register")
    public String register(User user)
    {
        ServiceResult result = this.service.register(user);
        return switch (result) {
            case SUCCESS -> "注册成功";
            case NULL_USERNAME -> "用户名为空";
            case NULL_PASSWORD -> "密码为空";
            case EXISTS_NAME -> "用户名已被使用";
            default -> "注册失败";
        };
    }
    

    @ResponseBody
    @PostMapping("/login")
    public String login(HttpSession session, User user)
    {
        ServiceResult result = this.service.login(user.getUsername(), user.getPassword());
        return switch (result) {
            case SUCCESS -> {
                session.setAttribute(SessionAttribute.USER.getName(), this.service.getUserByUsername(user.getUsername()));
                yield "登录成功";
            }
            case NULL_USERNAME -> "用户名为空";
            case NULL_PASSWORD -> "密码为空";
            case NOT_EXISTS_USER -> "用户不存在";
            default -> "登录失败";
        };
    }
    
}

